<?php

namespace Beerus\Modules\GoodsTest\Controllers;

use App\Pockets\GridDataModel;
use Biz\model\GoodsTestActivity\FineGoodsWishMsgModel;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Widgets\Form;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Illuminate\Routing\Redirector;
use Illuminate\Support\MessageBag;

/**
 * Description: 许愿词管理
 * Created by IntelliJ IDEA.
 * User: 玉坤
 * Date: 2021/7/16
 * Time: 18:36
 */
class WishMsgController extends Controller
{
    public const PAGE_SIZE = 20;

    public function index(Request $request, Content $content): Content
    {
        $params = $request->all();
        $page_size = $params['per_page'] ?? self::PAGE_SIZE;
        $params['per_page'] = $page_size;
        $list = FineGoodsWishMsgModel::all(['id[>]' => 0]);
        $count = count($list);
        $gridModel = new GridDataModel($list, $count, [
            'perPage' => $page_size,
        ]);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableFilter();
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'id')->sortable();
                $grid->column('emoji_url', '商品图片')->display(function ($emoji_url) {
                    $emoji_url = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $emoji_url, ImgUrl::IMAGE_SIZE_ORI_NPHONE) ?? '';
                    return '<a href="javascript:layer.open({type: 2,title: \'预览\',maxmin: true,area: [\'400px\', \'400px\'],content: \'' . $emoji_url . '\'});">
                                <img width="100px" height="100px" src="' . $emoji_url . '">
                            </a>';
                });

                $grid->column('wish_type', '内容类型')->using(
                    [
                        FineGoodsWishMsgModel::WISH_NORMAL => '普通',
                        FineGoodsWishMsgModel::WISH_SPECIAL => '自定义',
                    ]
                )->label([
                    2 => 'success',
                    1 => 'info',
                ]);
                $grid->column('content', '内容')->width(200);

                $grid->column('wish_status', '删除状态')->using(
                    [
                        FineGoodsWishMsgModel::STATUS_NORMAL => '正常',
                        FineGoodsWishMsgModel::STATUS_DELETED => '删除',
                    ]
                )->label([
                    FineGoodsWishMsgModel::STATUS_NORMAL => 'success',
                    FineGoodsWishMsgModel::STATUS_DELETED => 'danger',
                ]);

                $grid->setActionClass(Actions::class);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableView();
                });
            }
        );

        $content->row($grid);
        return $content
            ->header('许愿词列表')
            ->description(' ')
            ->breadcrumb(['text' => '许愿词列表', 'url' => '/goodsTest/wish/list']);
    }


    /**
     * 编辑
     * @param $id
     * @param Content $content
     * @return Content|Application|RedirectResponse|Redirector
     */
    public function edit($id, Content $content)
    {
        if (!$id) {
            admin_error('参数错误！', 'warning');
        }
        $where['id'] = $id;
        //编辑wiki
        $wishInfo = FineGoodsWishMsgModel::first($where);

        if (!$wishInfo) {
            $error = new MessageBag([
                'title' => '信息不存在或已删除',
            ]);

            return back()->with(compact('error'));
        }
        $baseForm = new Form($wishInfo);
        $baseForm->imgUpload('emoji_url', 'emoji', true, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BIZ,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE,
        ])->help("仅支持一张图片上传");
        $baseForm->hidden('id');
        $baseForm->text('content', '内容');
        $baseForm->confirm('确定更新吗？');
        $baseForm->action('/admin/goodsTest/wish/save');

        return $content
            ->header('修改')
            ->description(' ')
            ->breadcrumb(
                ['text' => '许愿词列表', 'url' => '/goodsTest/wish/list'],
                ['text' => '许愿词修改']
            )
            ->row($baseForm);

    }

    /**
     * 保存修改
     * @param Request $request
     * @return Application|RedirectResponse|Redirector
     */
    public function Save(Request $request)
    {
        $params = $request->post();
        try {
            if (empty($params['id']) || $params['id'] <= 0) {
                throw new \Exception('非法提交');
            }
            $id = FineGoodsWishMsgModel::first(['id' => $params['id']], 'id');
            if (!$id) {
                throw new \Exception('该内容不存在！');
            }
            $emoji_url = isset($params['emoji_url']) ? explode(',', $params['emoji_url']) : [];
            //图片数量
            $count = count($emoji_url);
            if ($count > 1) {
                throw new \Exception('图片不能超过1张');
            }
            $where['id'] = $params['id'];

            $data['content'] = $params['content'];
            $data['emoji_url'] = $params['emoji_url'];
            FineGoodsWishMsgModel::update($data, $where);
            $success = new MessageBag([
                'title' => '提交成功'
            ]);

        } catch (\Exception $e) {
            $error = new MessageBag(['title' => $e->getMessage()]);
            return redirect('/admin/goodsTest/wish/list/' . $params['id'] . '/edit')->with(compact('error'));
        }
        return redirect('/admin/goodsTest/wish/list/' . $params['id'] . '/edit')->with(compact('success'));
    }
}